package adventure.commands;

import adventure.*;
import player.*;

/**
 *
 * @author Michael Hanns
 *
 */
public class Subscriptions extends AbstractCommand {

    public Subscriptions(Adventure a) {
        super(a, new String[]{"SUBSCRIBE", "SUBSCRIPTIONS", "GENERAL", "TRADE",
                    "NEWBIE", "OOC"});
    }

    @Override
    public String validateAndExecute(Player p, String[] args) {
        if (args.length == 1 && ("SUBSCRIBE".startsWith(args[0].toUpperCase())
                || "SUBSCRIPTIONS".startsWith(args[0].toUpperCase()))) {
            return p.subscribeTo("");
        } else if (args.length == 1) {
            return p.subscribeTo(args[0]);
        } else if (args.length == 2 && "SUBSCRIBE".startsWith(args[0].toUpperCase())) {
            return p.subscribeTo(args[1]);
        } else if (args.length >= 2 && !"SUBSCRIBE".startsWith(args[0].toUpperCase())
                && !"SUBSCRIPTIONS".startsWith(args[0].toUpperCase())) {
            return broadcastToChannel(p, args[0], Util.consolidateArguments(args));
        } else {
            return "Command not recognised.";
        }
    }

    private String broadcastToChannel(Player player, String channel, String message) {
        if (player.subscribesTo(channel)) {
            out.broadcastOnChannel(channel, message, player.getName());
            return "";
        } else {
            String output = player.subscribeTo(channel);
            out.broadcastOnChannel(channel, message, player.getName());
            return output;
        }
    }
}
